// 这是配置路由的文件
import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入组件
import Login from '@/views/Login'
import Reg from '@/views/Reg'
import Layout from '@/views/Layout'
import Home from '@/views/Home'
import Artcategory from '@/views/Artcategory'
import ArtList from '@/views/ArtList'
import UserInfor from '@/views/UserInfor'
import ChangeAvatar from '@/views/ChangeAvatar'
import ResetPwd from '@/views/ResetPwd'
Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    // 路径和组件
    { path: '/login', component: Login },
    { path: '/reg', component: Reg },
    {
      path: '/',
      component: Layout,
      children: [
        { path: '/', component: Home },
        { path: '/artcategory', component: Artcategory },
        { path: '/artlist', component: ArtList },
        { path: '/userinfor', component: UserInfor },
        { path: '/changeavatar', component: ChangeAvatar },
        { path: '/resetpwd', component: ResetPwd }
      ]
    }
  ]
})
// 路由前置导航守卫
// 白名单列表
const whileList = ['/login', '/reg']
router.beforeEach((to, from, next) => {
  // 先判断是否访问的是有权限的页面
  if (whileList.includes(to.path)) {
    // 用户访问的是登录或者注册页面 不需要拦截 直接放行
    next()
  } else {
    // 进入else分支说明用户访问的是有权限的页面, 先判断是否有token
    // 如果有token直接放行
    if (localStorage.getItem('token')) {
      next()
    } else {
      // 没有token拦截到登录页面让用户重新登录
      next({ path: '/login' })
    }
  }
})

export default router
